package gs.eisenhower.swallet.dao;

import gs.eisenhower.swallet.db.WalletSqlHelper;
import gs.eisenhower.swallet.utils.constants.WalletConstants;
import gs.eisenhower.swallet.utils.methods.QueryBuilder;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import android.database.Cursor;

public class BudgetDaoImpl extends GenericDaoImpl implements BudgetDao {
	
	public BudgetDaoImpl() {
	}
	
	@Override
	public Double read() {
		QueryBuilder queryBuilder = new QueryBuilder();
		queryBuilder.SELECT(WalletSqlHelper.AMOUNT_COLUMN);
		queryBuilder.FROM(WalletSqlHelper.BUDGET_TABLE_NAME);

		Cursor cursor = open().rawQuery(queryBuilder.toString(), null);
		double amount = 0.0;
		if (cursor.moveToFirst() && cursor.isLast()) {
			amount = cursor.getDouble(0);
		} else if (cursor.moveToFirst()) {
			while (cursor.moveToNext()) {
				if (cursor.isLast()) {
					amount = cursor.getDouble(0);
				}
			}
		}
		cursor.close();
		close();

		return amount;
	}
	
	@Override
	public Map<String, Double> readAll() {
		QueryBuilder queryBuilder = new QueryBuilder();
		queryBuilder.SELECT(WalletSqlHelper.AMOUNT_COLUMN + WalletConstants.COMMA
				+ WalletSqlHelper.BUDGET_TRANSACTION_DATE);
		queryBuilder.FROM(WalletSqlHelper.BUDGET_TABLE_NAME);

		Cursor cursor = open().rawQuery(queryBuilder.toString(), null);
		Map<String, Double> allTransactions = new TreeMap<String, Double>();
		if (cursor.moveToFirst()) {
			do {
				allTransactions.put(cursor.getString(1), cursor.getDouble(0));
			} while (cursor.moveToNext());
		}
		cursor.close();
		close();

		return allTransactions;
	}

	@Override
	public List<String> readTransactionDates() {
		QueryBuilder queryBuilder = new QueryBuilder();
		queryBuilder.SELECT(WalletSqlHelper.ID_COLUMN + WalletConstants.COMMA
				+ WalletSqlHelper.BUDGET_TRANSACTION_DATE);
		queryBuilder.FROM(WalletSqlHelper.BUDGET_TABLE_NAME);
		queryBuilder.ORDER_BY_DESC();
		
		List<String> transactionDates = new ArrayList<String>();
		Cursor cursor = open().rawQuery(queryBuilder.toString(), null);
		if (cursor.moveToFirst()) {
			do {
				transactionDates.add(cursor.getString(1));
			} while (cursor.moveToNext());
		}
		cursor.close();
		close();
		
		return transactionDates;
	}
}
